// pages/post/post.js
const app = getApp();
import PermissionManager from "../../utils/permission.js";
import LocationHelper from "../../utils/location.js";
import CameraHelper from "../../utils/camera.js";

Page({
  data: {
    content: "",
    images: [],
    topics: [
      { id: 1, name: "萌宠日常", selected: false },
      { id: 2, name: "宠物健康", selected: false },
      { id: 3, name: "宠物训练", selected: false },
      { id: 4, name: "宠物美食", selected: false },
      { id: 5, name: "宠物摄影", selected: false },
      { id: 6, name: "宠物用品", selected: false },
    ],
    location: "",
    canPublish: false,
  },

  onLoad() {
    this.checkCanPublish();
  },

  // 内容输入
  onContentInput(e) {
    this.setData({
      content: e.detail.value,
    });
    this.checkCanPublish();
  },

  // 选择图片
  async chooseImage() {
    try {
      const imagePaths = await CameraHelper.chooseImage({
        count: 9 - this.data.images.length,
      });

      if (imagePaths && imagePaths.length > 0) {
        this.setData({
          images: [...this.data.images, ...imagePaths],
        });
        this.checkCanPublish();
      }
    } catch (err) {
      console.log("选择图片失败:", err);
      wx.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    }
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    images.splice(index, 1);
    this.setData({ images });
    this.checkCanPublish();
  },

  // 切换话题选择
  toggleTopic(e) {
    const id = e.currentTarget.dataset.id;
    const topics = this.data.topics.map((topic) => {
      if (topic.id === id) {
        topic.selected = !topic.selected;
      }
      return topic;
    });
    this.setData({ topics });
  },

  // 选择位置
  async chooseLocation() {
    try {
      const locationInfo = await LocationHelper.chooseLocation();
      if (locationInfo) {
        this.setData({
          location: locationInfo.name,
        });
      }
    } catch (err) {
      console.log("位置选择失败:", err);
      wx.showToast({
        title: "位置选择失败",
        icon: "none",
      });
    }
  },

  // 检查是否可以发布
  checkCanPublish() {
    const canPublish =
      this.data.content.trim().length > 0 || this.data.images.length > 0;
    this.setData({ canPublish });
  },

  // 发布帖子
  publishPost() {
    if (!this.data.canPublish) return;

    const selectedTopics = this.data.topics.filter((topic) => topic.selected);

    wx.showLoading({
      title: "发布中...",
    });

    // 模拟发布过程
    setTimeout(() => {
      wx.hideLoading();

      wx.showToast({
        title: "发布成功",
        icon: "success",
      });

      // 返回首页
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/index/index",
        });
      }, 1500);
    }, 2000);
  },

  onUnload() {
    // 页面卸载时清理数据
    this.setData({
      content: "",
      images: [],
      topics: this.data.topics.map((topic) => ({ ...topic, selected: false })),
      location: "",
    });
  },
});
